/*
 * @Author: HeAo
 * @Date: 2021-11-02 14:30:58
 * @LastEditTime: 2021-11-02 16:14:36
 * @LastEditors: HeAo
 * @Description:
 * @FilePath: \web2103-2105\web2105\4-1-Nodejs\day03\1-http.js
 * 别乱动！
 */
let http = require('http');
let url = require('url');
let qs = require('querystring');

// 封装响应结果
class Response {
  constructor(message, data) {
    this.message = message
    this.data = data
    this.status = 20000
    this.timestamp = new Date().getTime()
  }
}

http.createServer((req, res) => {
  let urlObj = url.parse(req.url)
  // console.log(urlObj);
  switch (urlObj.pathname) {
    case '/user/findAll':
      const users = [
        { id: 1, name: 'terry', age: 12 },
        { id: 2, name: 'larry', age: 12 },
        { id: 3, name: 'tom', age: 12 },
      ]
      // 设置响应行以及响应头信息
      res.writeHead(200, 'SUCCESS', {
        'Content-Type': 'application/json'
      })

      // 设置响应体参数
      res.write(JSON.stringify(new Response('查询成功', users)))
      res.end()
      break;
    case '/user/deleteById':
      const id = qs.parse(urlObj.query).id
      console.log(id);
      res.writeHead(200, 'OK', {
        'Content-Type': 'appliation/json'
      })
      res.write(JSON.stringify(new Response('删除成功', null)))
      res.end()
      break;
    case '/user/saveOrUpdate':
      let data = []
      req.on('data', (chunk) => {
        data += chunk
        data = qs.parse(data)

        if (data.id) {
          res.write(JSON.stringify(new Response('修改成功', null)))
          res.end()
        } else {
          res.write(JSON.stringify(new Response('保存成功', null)))
          res.end()
        }
      })
      // console.log('out', data);

      break;
  }

  // /user/findAll
  // /user/deleteById
  // /user/saveOrUpdate
  // /user/findById
  // 结束响应

}).listen(3000, () => {
  console.log('3000server is running');
})



